<?php
namespace app\admin\controller;

use app\common\model\MemberModel;
use app\common\service\NoticeService;
use common\util\ArrayUtil;
use think\Db;
use web\util\WebUtil;
use common\util\Tools;
use web\util\MemberUtil;
use app\common\service\MsgService;

class Recharge extends Base {
    
    /*
     * 初始化操作
     */
    public function _initialize(){
        $this->needLogin();
        
    }
    
    // 充值列表
    public function index() {
        return $this->fetch();
    }

    // 充值记录
    public function record() {
        $mid = $this->request->param('mid',0);
        $this->assign('mid',$mid);
        return $this->fetch();
    }

    /**
     * 充值接口
     */
    public function rs() {
        $adminId = $this->getLoginId();
        if(empty($adminId)){
            return $this->returnResult(-7,'未登录');
        }
        $status = $this->request->param('status', '');
        $start = $this->request->param('start',0);
        $startDate = $this->request->param('start_date', '');
        $endDate = $this->request->param('end_date', '');
        $name = $this->request->param('name', '');
        
        $draw = $this->request->param('draw', '1', 'intval');
        if (empty($draw) || $draw <= 0) {
            $draw = 1;
        }
        
        $type = 1;
        // 充值
        $table = 'recharge';
        $db = Db::name($table);
        
        $where['type'] = $type;
        $where['recharge_type'] =  1;
        if ($status != '') {
            $where['ifpass'] =  $status;
        }
        if ($startDate) {
            $where['addtime'] = ['>', date('Y-m-d', strtotime($startDate))];
        }
        if ($endDate) {
            $where['addtime']= ['<', date('Y-m-d 23:59:59', strtotime($endDate))];
        }
        if($startDate && $endDate){
            $where['addtime'] = [ 'between',[date('Y-m-d', strtotime($startDate)), date('Y-m-d 23:59:59', strtotime($endDate))]];
        }
        if($name){
            $mids = MemberModel::instance()->searchMidsByKeywords($name);;
            $where['mid'] = ['in',$mids];
        }
        $size = 10;
        
        $items = $db->where($where)->limit($start, $size)
            ->order('id', 'desc')
            ->select();
            $count = $db->where($where)->count();
        $list = [];
        $memberMap = [];
        $adminMap = [];
        
        $memberModel = Db::name('member');
        $adminModel = Db::name('admin');
        
        $mids = ArrayUtil::getKeyValuesFromArray($items, 'mid');
        $midMap = [];
        if($mids){
            $midMap= MemberModel::instance()->getItemsByIds($mids,'name,grade');
        }
        
        foreach ($items as $item) {
            $member = null;
            $adminName = '';
            $smid = $item['mid'];
            
            $adminId = $item['admin_id'];
            if ($adminId) {
//                 $admin = null;
//                 if (array_key_exists($adminId, $adminMap)) {
//                     $admin = $adminMap[$adminId];
//                 } else {
//                     $admin = $adminModel->where('id', $adminId)->find();
//                     $adminMap[$adminId] = $admin;
//                 }
                $adminName = '';
            }
            
            $temp = [
                'id' => $item['id'],
                'mid' => $item['mid'],
                'name' => $midMap[$smid]['name'],
                'pic' => $item['pic'],
                'money' => $item['money'],
                'remark' => $item['remark'],
                'status' => $item['ifpass'],
                'admin_name' => $adminName,
                'status_name' => WebUtil::getStatusName($item['ifpass']),
                'ctime' => date('Y/m/d H:i:s', strtotime($item['addtime'])),
                'utime' => $item['updatetime'] != '0000-00-00 00:00:00' ? date('Y/m/d', 
                    strtotime($item['updatetime'])) : '-'
            ];
            $list[] = $temp;
        }
        $data = array(
            "returnCode" => 1,
            "returnMsg" => "success!",
            'recordsTotal' => $count,
            'recordsFiltered' => $count,
            'draw' => $draw,
            'data' => $list
        );
        return json($data);
    }

    public function pass() {
        $adminId = $this->getLoginId();
        if(empty($adminId)){
            return $this->returnResult(-7,'未登录');
        }
        $id = $this->request->param('id', '0');
        $remark = $this->request->param('remark', '0');
        if (empty($id)) {
            return $this->returnResult(- 1, '参数错误');
        }
        $db = Db::name('recharge');
        $item = $db->where('type', 1)
            ->where('id', $id)
            ->find();
        if (empty($item)) {
            return $this->returnResult(- 1, '不存在');
        }
        if ($item['ifpass'] != 0) { // 未审核
            return $this->returnResult(- 1, '已经审核');
        }
        
        Db::transaction(
            function () use($id, $adminId, $remark, $item) {
                Db::name('recharge')->where('id', $id)->update(
                    [
                        'ifpass' => 1,
                        'updatetime' => date('Y-m-d H:i:s', time()),
                        'admin_id' => $adminId,
                        'remark' => $remark
                    ]);
                Db::name('member')->where('id', $item['mid'])->setInc('account', $item['money']);
            });
        
        $member = MemberModel::instance()->find($item['mid']);
        if($member['openid']){
            MsgService::sendRechargeSuccessMsg($member['openid'], $item['money'],MemberUtil::getTotalAccount($member), $item['addtime']);
        }
        
        return $this->returnResult(1, '成功');
    }
    
    

    public function unpass() {
        $adminId = $this->getLoginId();
        if(empty($adminId)){
            return $this->returnResult(-7,'未登录');
        }
        $id = $this->request->param('id', '0');
        $remark = $this->request->param('remark', '0');
        if (empty($id)) {
            return $this->returnResult(- 1, '参数错误');
        }
        $db = Db::name('recharge');
        
        $item = $db->where('type', 1)
            ->where('id', $id)
            ->find();
        if ($item['ifpass'] != 0) { // 未审核
            return $this->returnResult(- 1, '已经审核');
        }
        if (empty($item)) {
            return $this->returnResult(- 1, '不存在');
        }
        
        $db->where('id', $id)->update(
            [
                'ifpass' => 2,
                'updatetime' => date('Y-m-d H:i:s', time()),
                'admin_id' => $adminId,
                'remark' => $remark
            ]);
        $member = MemberModel::instance()->find($item['mid']);
        if($member['openid']){
            MsgService::sendRechargeFailMsg($member['openid'],Tools::getDisplayDate(),$remark);
        }
        return $this->returnResult(1, '成功');
    }
    
    //首次注册充值
    public function first_add(){
        $adminId = $this->getLoginId();
        if(empty($adminId)){
            return $this->returnResult(-7,'未登录');
        }
        $mid = $this->request->param('mid','0');
        $money = $this->request->param('money','0');
        $remark = $this->request->param('remark','');
        $yajin = $this->request->param('yajin','');
        
        $data = [
            'mid'=>$mid,
            'type'=>1,
            'money'=>$money,
            'cash_name'=>'注册充值',
            'addtime'=> Tools::getCurDate(),
            'pic'=>'',
            'ifpass' => 1,
            'updatetime' => Tools::getCurDate(),
            'admin_id' => $adminId,
            'remark' => $remark,
            'recharge_type'=>2,
            'date'=>date('Ymd')
        ];
        
        $result = false;
        $msg= '';
        Db::startTrans();
        try{
            if($money > 0){
                Db::name('recharge')->insert($data);
            }
            
            Db::name('member')->where('id', $mid)->inc('account', $money)->inc('yajinaccount',$yajin)->update();
            // 提交事务
            Db::commit();
            $result = true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $msg= $e->getMessage();
        }
        if($result){
            $member = MemberModel::instance()->find($mid);
            if($member['openid'] && $money){
                MsgService::sendRechargeSuccessMsg($member['openid'], $money, MemberUtil::getTotalAccount($member),Tools::getCurDate(),$remark);
            }
            return $this->returnResult(1);
        }else{
            return $this->returnResult(-1,$msg);
        }
    }
    /**
     * 后台添加充值
     */
    public  function add(){
        $adminId = $this->getLoginId();
        if(empty($adminId)){
            return $this->returnResult(-7,'未登录');
        }
        $mid = $this->request->param('mid','0');
        $money = $this->request->param('money','0');
        $remark = $this->request->param('remark','');
        
        $data = [
            'mid'=>$mid,
            'type'=>1,
            'money'=>$money,
            'cash_name'=>'后台充值',
            'addtime'=> Tools::getCurDate(),
            'pic'=>'',
            'ifpass' => 1,
            'updatetime' => Tools::getCurDate(),
            'admin_id' => $adminId,
            'remark' => $remark,
            'recharge_type'=>2,
            'date'=>date('Ymd')
        ];
        
        $result = false;
        $msg= '';
        Db::startTrans();
        try{
            Db::name('recharge')->insert($data);
            Db::name('member')->where('id', $mid)->setInc('account', $money);
            // 提交事务
            Db::commit();
            $result = true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $msg= $e->getMessage();
        }
        if($result){
            $member = MemberModel::instance()->find($mid);
            if($member['openid'] && $money){
                MsgService::sendRechargeSuccessMsg($member['openid'], $money, MemberUtil::getTotalAccount($member),Tools::getCurDate(),$remark);
            }
            return $this->returnResult(1);
        }else{
            return $this->returnResult(-1,$msg);
        }
        
    }
    
    /**
     * 后台所有充值记录,用户提交和后台提交
     */
    public function all_rs(){

        $adminId = $this->getLoginId();
        if(empty($adminId)){
            return $this->returnResult(-7,'未登录');
        }
        $status = $this->request->param('status', '');
        $start = $this->request->param('start',0);
        $startDate = $this->request->param('start_date', '');
        $endDate = $this->request->param('end_date', '');
        $name = $this->request->param('name', '');
        $mid = $this->request->param('mid',0);
        
        $draw = $this->request->param('draw', '1', 'intval');
        if (empty($draw) || $draw <= 0) {
            $draw = 1;
        }
        
        $type = 1;
        // 充值
        $table = 'recharge';
        $db = Db::name($table);
        
        $where['type'] = $type;
        if ($status != '') {
            $where['ifpass'] = $status;
        }
        if ($startDate) {
            $where['addtime'] = ['>', date('Y-m-d', strtotime($startDate))];
        }
        if ($endDate) {
            $where['addtime']=[ '<', date('Y-m-d 23:59:59', strtotime($endDate))];
        }
        
        if($startDate && $endDate){
            $where['addtime'] = [ 'between',[date('Y-m-d', strtotime($startDate)), date('Y-m-d 23:59:59', strtotime($endDate))]];
        }
        
        if($name){
            $mids = MemberModel::instance()->searchMidsByKeywords($name);;
            $where['mid'] = ['in',$mids];
        }
        
        if ($mid) {
            $where['mid'] = $mid;
        }
        
        $size = 10;
        
        $items = $db->where($where)->limit($start, $size)
        ->order('id', 'desc')
        ->select();
        
        $count = $db->where($where)->count();
        $list = [];
        $adminMap = [];
        
        $memberModel = Db::name('member');
        $adminModel = Db::name('admin');
        
        $mids = ArrayUtil::getKeyValuesFromArray($items, 'mid');
        $midMap = [];
        if($mids){
            $midMap= MemberModel::instance()->getItemsByIds($mids,'name,tel,weixin,grade');
        }
        foreach ($items as $item) {
            $adminName = '';
            $smid = $item['mid'];
            $adminId = $item['admin_id'];
            if ($adminId) {
                $admin = null;
//                 if (array_key_exists($adminId, $adminMap)) {
//                     $admin = $adminMap[$adminId];
//                 } else {
//                     $admin = $adminModel->where('id', $adminId)->find();
//                     $adminMap[$adminId] = $admin;
//                 }
//                 $adminName = $admin['name'];
                $adminName = '总部';
            }
        
            $temp = [
                'id' => $item['id'],
                'mid'=>$smid,
                'name' => $midMap[$smid]['name'],
                'remark' => $item['remark'],
                'tel'=>$midMap[$smid]['tel'],
                'weixin'=>$midMap[$smid]['weixin'],
                'grade'=>$midMap[$smid]['grade'],
                'pic' => $item['pic'],
                'money' => $item['money'],
                'status' => $item['ifpass'],
                'admin_name' => $adminName,
                'status_name' => WebUtil::getStatusName($item['ifpass']),
                'ctime' => date('Y/m/d H:i:s', strtotime($item['addtime'])),
                'utime' => $item['updatetime'] != '0000-00-00 00:00:00' ? date('Y/m/d H:i:s',
                    strtotime($item['updatetime'])) : '-',
                'recharge_type'=>$item['recharge_type'],
                'recharge_type_name'=>WebUtil::getRechargeType($item['recharge_type']),
            ];
            $list[] = $temp;
        }
        $data = array(
            "returnCode" => 1,
            "returnMsg" => "success!",
            'recordsTotal' => $count,
            'recordsFiltered' => $count,
            'draw' => $draw,
            'data' => $list
        );
        return json($data);
        
    }
    
    // 充值列表 | 详情
    public function detail() {
        return $this->fetch();
    }
}
